<?php
function getOgTags($html)
{
    $pattern='/<\s*meta\s+property="og:([^"]+)"\s+content="([^"]*)/i';
    if(preg_match_all($pattern, $html, $out))
        return array_combine($out[1], $out[2]);
    return array();
}


function parseMarkdown($text) {
    // Convert bold (**text**) to <b>text</b>
    $text = preg_replace('/\*\*(.*?)\*\*/', '<b>$1</b>', $text);
    
    // Convert italic (*text*) to <i>text</i>
    $text = preg_replace('/\*(.*?)\*/', '<i>$1</i>', $text);
    
    // Convert underline (_text_) to <u>text</u>
    $text = preg_replace('/__(.*?)__/', '<u>$1</u>', $text);
    
    // Convert (((text))) to <pre>text</pre>
    $text = preg_replace('/\(\(\((.*?)\)\)\)/s', '<pre>$1</pre>', $text);
    
    return $text;
}

function getSiteName($url) {
    // Parse the URL to get the hostname
    $host = parse_url($url, PHP_URL_HOST);

    if (!$host) {
        return "Invalid URL.";
    }

    // Break the hostname into parts (split by '.')
    $parts = explode('.', $host);

    // Handle cases like 'boards.4chan.org' or 'www.google.com'
    $numParts = count($parts);
    if ($numParts > 2) {
        // If there are more than two parts, extract the second-to-last part
        $coreDomain = $parts[$numParts - 2];
    } else {
        // Otherwise, take the first part of the hostname
        $coreDomain = $parts[0];
    }

    // Capitalize the first letter to make it look like a proper name
    return ucfirst($coreDomain);
}

function getPageTitle($url) {
    // Fetch the HTML content of the webpage
    exec("wget -O htt.html --user-agent=\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36\" $url");
	$html = file_get_contents("htt.html");
    if ($html === false) {
        return "Unable to fetch content from the URL.";
    }

    // Define regex pattern for the <title> tag
    $titlePattern = '/<title>(.*?)<\/title>/is';

    // Match the <title> tag
    if (preg_match($titlePattern, $html, $matches)) {
        return trim($matches[1]);
    }
	@unlink("htt.html");
    return null;
}

function getMetaTags($url) {
	exec("wget -O htt.html --user-agent=\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36\" $url");
	$html = file_get_contents("htt.html");
	
    // Fetch the HTML content of the webpage
    $html = file_get_contents("htt.html");
    if ($html === false) {
        return "Unable to fetch content from the URL.";
    }
    
    // Define regex patterns for Open Graph and Twitter Card meta tags
    $metaPattern = '/<meta\s+(?:property|name)=["\'](og:[^"\']+|twitter:[^"\']+)["\']\s+[^>]*content=["\']([^"\']+)["\']\s*\/?>/i';
    
    // Initialize arrays to store the extracted information
    $metaData = [
        'openGraph' => [],
        'twitterCards' => []
    ];
    
    // Match all relevant meta tags
    if (preg_match_all($metaPattern, $html, $matches)) {
        foreach ($matches[1] as $key => $metaName) {
            $content = $matches[2][$key];
            if (strpos($metaName, 'og:') === 0) {
                // Open Graph tag
                $metaData['openGraph'][substr($metaName, 3)] = $content;
            } elseif (strpos($metaName, 'twitter:') === 0) {
                // Twitter Card tag
                $metaData['twitterCards'][substr($metaName, 8)] = $content;
            }
        }
    }
    @unlink("htt.html");
    return $metaData;
}


function renderPage($content){
	GLOBAL $loc_string;
	$output = file_get_contents("./templates/genericpage.txt");
	$output = str_replace("#content#",$content,$output);
	return $output;
}

function str_replace_once($haystack, $needle, $replace){
	$pos = strpos($haystack, $needle);
	if ($pos !== false) {
	    $newstring = substr_replace($haystack, $replace, $pos, strlen($needle));
	}
	return $newstring;
}